package com.qiyun.dinghuohui.utils;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

public class AsyncJsonTask extends AsyncTask<JSONObject, String, ServerResponse> {
    private ResultListener listener;
    private static final int SUCCESS = 0;
    private static final int FAIL = 1;

    private static final ServerResponse FAIL_RESPONSE = new ServerResponse(FAIL, "获取数据失败");
    protected String mModuleUrl = "";
    protected String mainUrl = "";

    public AsyncJsonTask(String mainUrl, String mModuleUrl, ResultListener listener) {
        this.listener = listener;
        this.mModuleUrl = mModuleUrl;
        this.mainUrl = mainUrl;
    }

    @Override
    protected final ServerResponse doInBackground(JSONObject... params) {
        listener.onPostDataStart();
        try {
            Log.i("request remote", mainUrl + mModuleUrl + "?jsonData=" + params[0].toString());
            JSONObject data = HttpDataFetcher.getInstance().postData(mainUrl, mModuleUrl, params[0]);
            return new ServerResponse(SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FAIL_RESPONSE;
    }

    @Override
    protected final void onPostExecute(ServerResponse result) {
        try {
            if (result.code == SUCCESS) {
                listener.onPostDataSuccess(result);
                try {
                    JSONObject resultJson = result.result;
                    if (resultJson != null && resultJson.length() != 0) {
                        LogUtil.d("AsyncJsonTask", "return_json__" + resultJson.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                listener.onPostDataError(result);
            }
        } catch (Exception e) {
            listener.onPostDataError(result);
            e.printStackTrace();
        }
        listener.onPostDataComplete(result);
    }

    @Override
    protected final void onProgressUpdate(String... values) {
        listener.setProgressMessage(values[0]);
    }
}
